package com.xcw.jac.des;

import java.security.*;
import javax.crypto.*;
import java.util.Base64;

public class Encryptor {
    private KeyPair keyPair;

    public Encryptor() {
        try {
            // 生成RSA密钥对
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512);
            this.keyPair = keyPairGenerator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public String encrypt(String password) {
        try {
            // 获取公钥
            PublicKey publicKey = keyPair.getPublic();

            // 创建密码器
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            // 加密密码
            byte[] encryptedBytes = cipher.doFinal(password.getBytes());

            // 使用Base64编码转换为字符串
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getPublicKey() {
        // 获取公钥并转换为Base64编码的字符串
        return Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
    }

    public String getPrivateKey() {
        // 获取私钥并转换为Base64编码的字符串
        return Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
    }

    public static void main(String[] args) {
        String password = "root";

        Encryptor encryptor = new Encryptor();
        String encryptedPassword = encryptor.encrypt(password);
        String publicKey = encryptor.getPublicKey();
        String privateKey = encryptor.getPrivateKey();

        System.out.println("Encrypted Password: " + encryptedPassword);
        System.out.println("Public Key: " + publicKey);
        System.out.println("Private Key: " + privateKey);
    }

}